<template>
	<div class="user-choose">
		<Button @click="userModalVisible=true" :icon="icon">{{text}}</Button>
		<span @click="clearSelectData" class="clear">清空已选</span>
		<Collapse simple class="collapse">
			<Panel name="1">
				已选择
				<span class="select-count">{{selectUsers.length}}</span> 人
				<p slot="content">
					<Tag v-for="(item, i) in selectUsers" :key="i" :name="item.id" color="default" closable @on-close="handleCancelUser">
						<span v-if="item.isExhibitor">{{item.companyName}}</span>
						<span v-else>{{item.nickName}}</span>
					</Tag>
				</p>
			</Panel>
		</Collapse>
		<Drawer title="选择用户" closable v-model="userModalVisible" :width="drawerWidth" draggable>
			<Form ref="searchUserForm" :model="searchUserForm" inline :label-width="80">
				<Form-item label="公司名称" prop="companyName">
					<Input type="text" v-model="searchUserForm.companyName" clearable placeholder="请输入公司名称" style="width: 150px" />
				</Form-item>
				<Form-item label="姓名" prop="nickName">
					<Input type="text" v-model="searchUserForm.nickName" clearable placeholder="请输入姓名" style="width: 150px" />
				</Form-item>
				<Form-item label="手机" prop="mobile">
					<Input type="text" v-model="searchUserForm.mobile" clearable placeholder="请输入手机" style="width: 150px" />
				</Form-item>
				<FormItem label="角色" prop="roleId">
					<Select v-model="searchUserForm.roleId"  placeholder="请选择角色" style="width: 150px">
						<Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.name">
							<span style="margin-right:10px;">{{ item.description}}</span>
							<span style="color:#ccc;">{{ item.name }}</span>
						</Option>
					</Select>
				</FormItem>
				<Form-item style="margin-left:-35px;" class="br">
					<Button @click="handleSearchUser" type="primary" icon="ios-search">搜索</Button>
					<Button @click="handleResetUser">重置</Button>
					<Button @click="chooseUsers" type="primary" style="margin-left:10px">批量添加用户</Button>
				</Form-item>
			</Form>
			<Table  :loading="userLoading" border :columns="userColumns" :data="userData" :height="height" ref="userTable" @on-selection-change="showSelect"></Table>
			
			<div class="my-drawer-footer" :style="{width:drawerWidth+'px',right:0}">
				<Row type="flex" justify="space-between" style="margin: 10px 0;">
				<Col>
				已选择
				<span class="select-count">{{selectUsers.length}}</span> 人
				<Button @click="clearSelectData" style="margin-left:10px" size="small">清空已选</Button>
				<Button @click="userModalVisible=false" type="primary" style="margin-left:10px"  size="small">关闭</Button>
				</Col>
					<Col>
				<Page :current="searchUserForm.pageNumber" :total="totalUser" :page-size="searchUserForm.pageSize" @on-change="changeUserPage"
				 @on-page-size-change="changeUserPageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator
				 show-sizer></Page>
				 </Col>
				 </Row>
			</div>
		</Drawer>
	</div>
</template>

<script>
	import {
		getUserListDataByChoose,
		getAllRoleList
	} from "@/api/index";
	export default {
		name: "userChoose",
		components: {},
		props: {
			text: {
				type: String,
				default: "选择用户"
			},
			icon: {
				type: String,
				default: "md-person-add"
			}
		},
		data() {
			return {
				drawerWidth:800,
				height: 500,
				userLoading: true,
				userModalVisible: false,
				selectUsers: [],
				searchUserForm: {
					roleId:'',
					username: "",
					type: "",
					status: "",
					pageNumber: 1, // 当前页数
					pageSize: 10, // 页面大小
					sort: "createTime", // 默认排序字段
					order: "desc" // 默认排序方式
				},
				userColumns: [
					{
					    type: "selection",
					    width: 60,
					    align: "center",
					    fixed: "left"
					},
					{
						type: "index",
						width: 60,
						align: "center"
					},
					{
						title: "用户",
						sortable: true,
						width: 200,
						render: (h, params) => {
							let nodes = [];
							let roles = params.row.roles;
							if (roles) {
								for (let i = 0; i < roles.length; i++) {
									let role = roles[i];
									nodes.push(
										h(
											"Tag", {
												props: {
													color: "orange"
												}
											},
											role.description
										)
									);
								}
							}
							nodes.push(h('span', {}, this.isExhibitor(params.row) ? params.row.username : params.row.nickName))

							return h("div", [
								nodes
							]);
						}
					},
					{
						title: "手机",
						key: "mobile",
						width: 125,
						render: (h, params) => {
							let nodes = [];
							nodes.push(h('span', {}, this.isUser(params.row) ? params.row.licenseeMobile : params.row.mobile))

							return h("div", [
								nodes
							]);
						}
					},
					{
						title: "姓名",
						key: "nickName",
						width: 125,
					},
					{
						title: "公司名称",
						key: "companyName",
						minWidth: 130,
					},
					{
						title: "创建时间",
						key: "createTime",
						sortable: true,
						sortType: "desc",
						width: 170
					},
					{
						title: "操作",
						key: "action",
						width: 130,
						align: "center",
						fixed: "right",
						render: (h, params) => {
							return h("div", [
								h(
									"Button", {
										props: {
											type: "info",
											size: "small"
										},
										on: {
											click: () => {
												this.chooseUser(params.row);
											}
										}
									},
									"添加该用户"
								)
							]);
						}
					}
				],
				userData: [],
				totalUser: 0,
				roleList:[],
				selectList: [],
			};
		},
		computed: {

			isExhibitor: function(v) {
				return function(v) {
					if (v.roles) {
						let d = v.roles.find((e) => {
							return e.name === 'ROLE_EXHIBITOR';
						});
						if (d) {
							return true;
						}
					}

					return false;
				}
			},
			isUser: function(v) {
				return function(v) {
					if (v.roles) {
						let d = v.roles.find((e) => {
							return e.name === 'ROLE_USER';
						});
						if (d) {
							return true;
						}
					}

					return false;
				}
			},
		},
		methods: {
			//获取全部职位（角色）
			getRoleList() {
				getAllRoleList().then(res => {
					if (res.success) {
						this.roleList  = res.result;
					}
				});
			},
			showSelect(e) {
			    this.selectList = e;
			},
			clearSelectAll() {
			    this.$refs.userTable.selectAll(false);
			},
			handleSelectDep(v) {
				this.searchUserForm.departmentId = v;
			},
			changeUserPage(v) {
				this.searchUserForm.pageNumber = v;
				this.getUserDataList();
			},
			changeUserPageSize(v) {
				this.searchUserForm.pageSize = v;
				this.getUserDataList();
			},
			getUserDataList() {
				this.userLoading = true;
				getUserListDataByChoose(this.searchUserForm).then(res => {
					this.userLoading = false;
					if (res.success) {
						this.userData = res.result.records;
						this.totalUser = res.result.total;
					}
				});
			},
			handleSearchUser() {
				this.searchUserForm.pageNumber = 1;
				this.searchUserForm.pageSize = 9;
				this.getUserDataList();
			},
			handleResetUser() {
				this.$refs.searchUserForm.resetFields();
				this.searchUserForm.pageNumber = 1;
				this.searchUserForm.pageSize = 9;
				this.$refs.dep.clearSelect();
				this.searchUserForm.departmentId = "";
				// 重新加载数据
				this.getUserDataList();
			},
			setData(v) {
				this.selectUsers = v;
				this.$emit("on-change", this.selectUsers);
			},
			chooseUser(v) {
				// 去重
				let that = this;
				let flag = true;
				this.selectUsers.forEach(e => {
					if (v.id == e.id) {
						that.$Message.warning("已经添加过啦，请勿重复选择");
						flag = false;
					}
				});
				if (flag) {
					let u = {
						id: v.id,
						username: v.username,
						companyName:v.companyName,
						nickName:v.nickName,
						isExhibitor:this.isExhibitor(v),
					};
					this.selectUsers.push(u);
					this.$emit("on-change", this.selectUsers);
					this.$Message.success(`添加用户成功`);
				}
			},
			//判断是否存在
			isExists(id){
				let flag = false;
				this.selectUsers.forEach(e => {
				    if (id == e.id) {
				        flag = true;
				    }
				});
				return flag;
			},
			isNotExists(id){
				return !this.isExists(id);
			},
			//批量添加用户
			chooseUsers() {
			    // 去重
			    let that = this;
				if (this.selectList.length == 0) {
				    this.$Message.warning("请先选择数据");
				    return;
				}
				let selectList = this.selectList;
				let arr = [];
				for (let i = 0; i < selectList.length; i++) {
					let v = selectList[i];
					if(this.isNotExists(v.id)){//如果不存在 则添加
						arr.push(v);
					}
				}
				if(arr.length>0){
					for (let i = 0; i < arr.length; i++) {
						let u = {
							id: arr[i].id,
							username: arr[i].username,
							companyName:arr[i].companyName,
							nickName:arr[i].nickName,
							isExhibitor:this.isExhibitor(arr[i]),
						};
						this.selectUsers.push(u);				
						
					}
					this.$emit("on-change", this.selectUsers);
				}
				this.clearSelectAll();
				this.$Message.success(`批量添加用户成功`);
			},
			clearSelectData() {
				this.selectUsers = [];
				this.$emit("on-change", this.selectUsers);
			},
			handleCancelUser(e, id) {
				// 删除所选用户
				let newArray = [];
				this.selectUsers.forEach(e => {
					if (id != e.id) {
						newArray.push(e);
					}
				});
				this.selectUsers = newArray;
				this.$emit("on-change", this.selectUsers);
				this.$Message.success("删除所选用户成功");
			}
		},
		created() {
			// 计算高度
			this.height = Number(document.documentElement.clientHeight - 230);
			this.drawerWidth = Math.max(Number(document.documentElement.clientWidth - 450),800);
			this.getUserDataList();
			this.getRoleList();
		}
	};
</script>

<style lang="less">
	.user-choose {
		.clear {
			font-size: 12px;
			margin-left: 15px;
			color: #40a9ff;
			cursor: pointer;
		}

		.collapse {
			font-size: 12px;
			margin-top: 15px;
			width: 500px;
		}

		.select-count {
			font-weight: 600;
			color: #40a9ff;
		}
	}

	.my-drawer-footer {
		z-index: 10;
		// width: 100%;
		position: absolute;
		bottom: 0;
		// left: 0;
		border-top: 1px solid #e8e8e8;
		padding: 4px 16px;
		text-align: right;
		background: #fff;
	}
</style>
